package com.lechi.web.framework.websocket;

import com.alibaba.fastjson2.JSON;
import com.lechi.web.common.utils.DateUtils;
import com.lechi.web.framework.log.IotExceptionLog;
import com.lechi.web.framework.manager.AsyncManager;
import com.lechi.web.system.domain.IotMonitorDataBo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 指令监听器
 */
@Slf4j
public class WebSocketUtil {

    /**
     * 发送到监控页面
     */
    public static void sendToMonitorPage(IotMonitorDataBo iotMonitorDataBo) {
        WebSocketMonitorData webSocketMonitorData = new WebSocketMonitorData();
        try {
            BeanUtils.copyProperties(iotMonitorDataBo, webSocketMonitorData);
            webSocketMonitorData.setDateTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, iotMonitorDataBo.getDateTime()));
            WebSocketServer.sendInfo(webSocketMonitorData.getDeviceId(), JSON.toJSONString(webSocketMonitorData));
        } catch (Exception e) {
            StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
            String method = Thread.currentThread().getName() + ":" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName();
            AsyncManager.me().execute(IotExceptionLog.exceptionLog(e, "webSocketServer sendToMonitorPage 服务发送异常", method, webSocketMonitorData));
            log.error("webSocketServer 服务异常: {}", e.getMessage(), e);
        }
    }

    /**
     * 发送到设备页面
     */
    public static void sendToDevicePage(String protocolType, List<IotMonitorDataBo> deviceDataList, String receiveData) {
        if (deviceDataList.isEmpty()) {
            return;
        }
        IotMonitorDataBo iotMonitorDataBo = deviceDataList.get(0);
        Function<IotMonitorDataBo, String> join = (IotMonitorDataBo monitorDataBo) -> monitorDataBo.getSensorAliasName() + "=" + monitorDataBo.getDoubleValue() + monitorDataBo.getUnit();
        final String analyse = deviceDataList.stream().map(join).collect(Collectors.joining(",  "));
        try {
            String dateTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, iotMonitorDataBo.getDateTime());
            if ("MODBUS-RTU".equals(protocolType)) {
                String message = IntStream.range(0, receiveData.length()).filter(i -> i % 2 == 0 && i < receiveData.length()).mapToObj(i -> receiveData.substring(i, i + 2)).collect(Collectors.joining(" "));
                WebSocketServer.sendInfo(iotMonitorDataBo.getDeviceId() + 1000, JSON.toJSONString(Map.of("record", message, "analyse", analyse, "time", dateTime)));
            } else {
                WebSocketServer.sendInfo(iotMonitorDataBo.getDeviceId() + 1000, JSON.toJSONString(Map.of("analyse", analyse, "time", dateTime)));
            }
        } catch (Exception e) {
            StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
            String method = Thread.currentThread().getName() + ":" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName();
            AsyncManager.me().execute(IotExceptionLog.exceptionLog(e, "webSocketServer 发送设备页面服务异常", method, iotMonitorDataBo));
            log.error("webSocketServer 发送设备页面服务异常: {}", e.getMessage(), e);
        }
    }
}
